<template>
  <div class="news">
    <!--    功能区域-->
    <div style="margin: 10px 0">
      <el-button type="primary" @click="addNews">发布新闻</el-button>
    </div>

    <!--    搜索区域-->
    <div style="margin: 10px 0">
      <el-input
        style="width: 20%"
        placeholder="请输入关键字"
        prefix-icon="el-icon-search"
        clearable
        v-model="search">
      </el-input>

      <el-button type="primary" plain @click="searchNews">搜索</el-button>
    </div>


    <!--    内容区域-->
    <!--    stripe：添加斑马纹-->
    <el-table
      :data="tableData"

      stripe

      border
      style="min-width: calc(100vh - 200px)">
      <!--      sortable：给日期一个排序按钮-->
      <!--      <el-table-column
              prop="id"
              label="ID">

            </el-table-column>-->

      <el-table-column
        label="序号"
        type="index">
      </el-table-column>

      <el-table-column
        prop="title"
        label="标题">

      </el-table-column>

      <el-table-column
        prop="author"
        label="作者">

      </el-table-column>


      <el-table-column
        prop="time"
        label="发布时间">

      </el-table-column>


      <el-table-column label="操作">
        <template slot-scope="scope">

          <el-button
            size="mini"
            @click="detail(scope.row)">详情
          </el-button>

          <el-button
            size="mini"
            @click="handleEdit(scope.row)">编辑
          </el-button>


          <el-popconfirm
            @confirm="deleteNews(scope.row)"
            confirm-button-text='好的'
            cancel-button-text='不用了'
            icon="el-icon-info"
            icon-color="red"
            title="删除后无法恢复！"
          >
            <el-button size="mini" type="danger" slot="reference">删除</el-button>
          </el-popconfirm>

        </template>
      </el-table-column>

    </el-table>

    <div style="margin: 10px 0">

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>

    </div>


    <!--    新增用户的表单-->
    <el-dialog title="请输入富文本信息" :visible.sync="dialogVisible" width="50%">
      <el-form :rules="rules" ref="form" :model="form" label-width="120px">

        <el-form-item label="标题：" prop="title">
          <el-input v-model="form.title" style="width: 50%"></el-input>
        </el-form-item>


        <el-form-item label="新闻：">
          <div id="div1"></div>
        </el-form-item>


        <!--        <el-form-item label="内容：" prop="content">
                  <el-input type="text" v-model="form.content" style="width: 70%"></el-input>
                </el-form-item>-->


      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="save('form')">确 定</el-button>
  </span>
    </el-dialog>


    <!--    新闻内容-->
    <el-dialog title="详情" :visible.sync="detailVis" width="50%">

      <el-card>
        <div v-html="details" style="min-height: 150px"></div>
      </el-card>

    </el-dialog>

  </div>
</template>

<script>
import request from "../unitls/request";
import E from 'wangeditor'//引入 富文本编辑器

//富文本对象
let editor;

export default {
  name: "News",
  //加载页面
  created() {
    this.load();
  },
  methods: {
    //详情弹窗（新闻内容）
    detail(row) {
      this.detailVis = true;
      console.log(row.content);
      this.details = row.content;
    },
    addNews() {
      this.dialogVisible = true;

      //打开则清空表单
      this.form = {};
      // editor =null;//刚打开时将富文本节点设为 null
      if (editor) {
        editor.txt.clear();
      } else {
        //在打开弹窗的时候， DOM 元素还没有加载出来，拿不到 #div1
        this.$nextTick(() => {//这个方法就是等 DOM元素加载完之后再执 行
          //打开弹窗就加载 创建富文本编辑
          editor = new E('#div1');

          // 配置 server 接口地址
          editor.config.uploadImgServer = 'http://localhost:8888/files/uploadDetail';
          editor.config.uploadFileName = 'file'; //设置文件上传的参数名称

          editor.create()
        })
      }

    },

    //搜索关键字
    searchNews() {
      this.load();
    },
    //编辑
    handleEdit(row) {

      //将传过来的row深拷贝给form
      this.form = JSON.parse(JSON.stringify(row));
      this.dialogVisible = true;


      this.$nextTick(() => {//这个方法就是等 DOM元素加载完之后再执行
        if (!editor) {
          //在打开弹窗的时候， DOM 元素还没有加载出来，拿不到 #div1

          //打开弹窗就加载 创建富文本编辑
          editor = new E('#div1');

          // 配置 server 接口地址
          editor.config.uploadImgServer = 'http://localhost:8888/files/uploadDetail';
          editor.config.uploadFileName = 'file'; //设置文件上传的参数名称

          editor.create()

        } else {
          editor.txt.clear();
        }

        editor.txt.html(row.content)//将行中的富文本内容赋值给编辑器
      })


    },
    //删除
    deleteNews(row) {
      request.delete("/api/news", {
        params: {
          id: row.id
        }
      }).then(success => {
          this.load();
          if (success.code === '0') {
            this.$notify({
              title: '删除成功',
              message: row.title + '删除成功！',
              type: 'success'

            });
          } else {
            this.$notify({
              title: '删除失败',
              message: success.msg,
              type: 'error'

            });
          }
        }
      )
    },

    //提交保存
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.content = editor.txt.html();//获取富文本编辑器里的值
          this.form.author = JSON.parse(sessionStorage.getItem("user")).username;//获得session对象（Login.vue里面设置了登录用户session）
          if (this.form.id) {
            request.put("/api/news", this.form).then(success => {
              this.load();
              this.dialogVisible = false;
              if (success.code === '0') {
                this.$notify({
                  title: '更新成功',
                  message: success.data + '更新成功！',
                  type: 'success'

                });
              } else {
                this.$notify({
                  title: '更新失败',
                  message: success.msg,
                  type: 'error'

                });
              }

            })
          } else {
            request.post("/api/news", this.form).then(success => {
              this.load();
              this.dialogVisible = false;
              console.log(success);
              if (success.code === '0') {
                this.$notify({
                  title: '发布成功',
                  message: success.data + '发布成功！',
                  type: 'success'
                });
              } else {
                this.$notify({
                  title: '发布失败',
                  message: success.msg,
                  type: 'error'

                });
              }
            })
          }
        }

      })
    },
    //改变当前页的数据个数
    handleSizeChange(val) {
      this.pageSize = val
      this.load();
    },

    //改变当前页的页码
    handleCurrentChange(val) {
      this.currentPage = val;
      this.load();
    },

    //查询数据
    load() {
      request.get("/api/news", {

        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          searchStr: this.search
        }

      }).then(success => {

        this.tableData = success.data.records;
        this.total = success.data.total;
      })
    },
  },
  data() {
    return {
      //富文本的详情
      details: '',
      //详情的弹窗
      detailVis: false,
      //form 新增数据的表单
      form: {},
      //表单是否打开
      dialogVisible: false,
      //搜索
      search: '',
      //当前页
      currentPage: 1,
      //一页有多少条数据
      pageSize: 10,
      //数据总数
      total: 0,
      //后端传过来的数据
      tableData: [],
      //定义规则
      rules: {
        title: [
          {required: true, message: '请输入标题', trigger: 'blur'},
          {min: 2, max: 11, message: '长度在 2 到 11 个字符', trigger: 'blur'}
        ],
      }
    }
  }
}
</script>

<style scoped>
.news {
  padding: 10px;
}

.avatar-uploader {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
